package 锁.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/9/5 14:58
 * @description: do和show共同争夺同一个锁，必须一个释放以后另一个才可以执行
 * @version:
 */
public class RenntrankLock_test {
    Lock lock = new ReentrantLock();
    public void doSth(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " " + "你好");
            Thread.sleep(4000);
            System.out.println(Thread.currentThread().getName() + " " +"你好结束");
            lock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void showSth(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " " +"hello");
            Thread.sleep(4000);
            System.out.println(Thread.currentThread().getName() + " " +"world");
            lock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void eatSth(){
        try {
            System.out.println(Thread.currentThread().getName() + " " +"eat");
            Thread.sleep(6000);
            System.out.println(Thread.currentThread().getName() + " " +"no eat");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


